package cn.itcast.algorithm.exercise;

import java.util.ArrayList;

/**
 * 获取数组中最小的k个元素
 * create by zhangtian105 on 2022/5/29
 */
public class ExerciseNC119 {
    public static void main(String[] args) {
        int[] input = new int[] {2,3,4,1,4,5} ;
        int k = 5 ;

        ArrayList<Integer> minKElements = getMinKElement(input, k) ;
        System.out.println(minKElements);
    }

    public static ArrayList<Integer> getMinKElement(int [] input, int k) {
        if (input == null) {
            return new ArrayList<>() ;
        }

        int length = input.length ;

        if (length == 0 || k > length) {
            return new ArrayList<>() ;
        }

        // 执行排序
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length - i - 1; j++) {
                if (input[j] > input[j+1]) {
                    int temp = input[j] ;
                    input[j] = input[j+1] ;
                    input[j+1] = temp ;
                }
            }
        }

        ArrayList<Integer> result = new ArrayList<>() ;
        for (int m = 0; m < k; m++) {
            result.add(input[m]) ;
        }

        return result ;
    }
}
